85 lines
2.1 KiB
C#
85 lines
2.1 KiB
C#
using Asp.Versioning;
|
||
using Microsoft.AspNetCore.Http;
|
||
using Microsoft.AspNetCore.Mvc;
|
||
using System.Collections.Generic;
|
||
using System.IO;
|
||
using System.Text;
|
||
|
||
namespace StoreHub.KJDWebService.Controllers
|
||
{
|
||
/// <summary>
|
||
/// API 控制器基类:提供与旧 asmx 一致的请求读取(body JSON,为空回退 QueryString)
|
||
/// 与响应输出(text/html;charset=utf-8 原始 JSON 字符串)。
|
||
/// </summary>
|
||
[ApiController]
|
||
[ApiVersionNeutral]
|
||
public abstract class BaseApiController : ControllerBase
|
||
{
|
||
/// <summary>
|
||
/// 读取请求参数:先读 body,body 为空时回退 QueryString,统一转换为 key=value&key=value 格式
|
||
/// (与旧 asmx 输入兼容,Manage 依赖 RegexUtils.GetStringQuery 解析 & 分隔的键值对)。
|
||
/// </summary>
|
||
protected string GetRequestJsonString()
|
||
{
|
||
Request.EnableBuffering();
|
||
string body = "";
|
||
using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8, true, 1024, true))
|
||
{
|
||
body = reader.ReadToEnd();
|
||
}
|
||
Request.Body.Position = 0;
|
||
|
||
if (string.IsNullOrEmpty(body))
|
||
{
|
||
var qs = Request.Query;
|
||
if (qs != null && qs.Count > 0)
|
||
{
|
||
var parts = new List<string>();
|
||
foreach (var key in qs.Keys)
|
||
{
|
||
parts.Add(key + "=" + qs[key].ToString());
|
||
}
|
||
return string.Join("&", parts);
|
||
}
|
||
return "";
|
||
}
|
||
|
||
// body 是 JSON 时转换为 key=value&key=value
|
||
string trimmed = body.Trim();
|
||
if (trimmed.StartsWith("{"))
|
||
{
|
||
try
|
||
{
|
||
var jObj = Newtonsoft.Json.Linq.JObject.Parse(trimmed);
|
||
var parts2 = new List<string>();
|
||
foreach (var prop in jObj.Properties())
|
||
{
|
||
parts2.Add(prop.Name + "=" + (prop.Value?.ToString() ?? ""));
|
||
}
|
||
return string.Join("&", parts2);
|
||
}
|
||
catch
|
||
{
|
||
// 不是合法 JSON,按原样返回
|
||
return body;
|
||
}
|
||
}
|
||
// 已是 key=value 或 form 格式
|
||
return body;
|
||
}
|
||
|
||
/// <summary>输出原始 JSON 字符串(与旧 Context.Response.Write 等价)</summary>
|
||
protected ContentResult WriteJson(string result)
|
||
{
|
||
return Content(result ?? "", "text/html;charset=utf-8", Encoding.UTF8);
|
||
}
|
||
}
|
||
}
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|