从asp.net framework框架切换到asp.net core框架,同样的功能,写法不一样
1、Request获取地址参数方法
1)framework
Request.QueryString["echoStr"]
2)core
HttpContext.Request.Query["echoStr"]
2、Response.Write()
1)framework
Response.Write(echoString);
Response.End();
2)core
/// <summary>
/// "text/html";
/// </summary>
/// <param name="response"></param>
/// <param name="content"></param>
public static void WriteTextHtml(this HttpResponse response, string content)
{
response.ContentType = "text/html";
using (StreamWriter sw = new StreamWriter(response.Body))
{
sw.Write(content);
}
}
/// <summary>
/// "application/json";
/// </summary>
/// <param name="response"></param>
/// <param name="content"></param>
public static void WriteJson(this HttpResponse response, string content)
{
response.ContentType = "application/json";
using (StreamWriter sw = new StreamWriter(response.Body))
{
sw.Write(content);
}
}
3、Request和Response
1)framework
HttpRequestBase Request = new HttpRequestWrapper(HttpContext.Current.Request);
HttpResponseBase Response = new HttpResponseWrapper(HttpContext.Current.Response);
2)core
var Request = HttpContextHelper.HttpContext.Current.Request;
var Response = HttpContextHelper.HttpContext.Current.Response;
4、Request.InputStream
1)framework
public static string ReturnString()
{
HttpRequestBase Request = new HttpRequestWrapper(HttpContext.Current.Request);
string postString = string.Empty;
if (Request.HttpMethod.ToUpper() == "POST")
{
//Request.InputStream - 只读 - 读取一次值后,会导致读取值结束,实质上就是指针移到了最后面
Stream stream = Request.InputStream;//new MemoryStream();
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
//设置当前流的位置为流的开始
stream.Seek(0, SeekOrigin.Begin);
Byte[] postBytes = new Byte[stream.Length];
stream.Read(postBytes, 0, (Int32)stream.Length);
postString = Encoding.UTF8.GetString(postBytes);
}
return postString;
}
#endregion
2)core
public static string ReturnString()
{
var Request = HttpContextHelper.HttpContext.Current.Request;
if (Request.Method.ToUpper() == "POST".ToUpper())
{
Request.EnableBuffering();
var stream = Request.Body;
long? length = Request.ContentLength;
if (length != null && length > 0)
{
// 使用这个方式读取,并且使用异步
StreamReader streamReader = new StreamReader(stream, Encoding.UTF8);
postString = streamReader.ReadToEndAsync().Result;
}
Request.Body.Position = 0;
}
return postString;
}
#endregion
未完待续。。。