如何执行跨域请求asp.net mvc?

时间:2016-10-19 09:22:02

标签: asp.net-mvc

以下是尝试使用

的示例代码
public ActionResult About()
    {
        WebRequest request = WebRequest.Create("");
        request.ContentType = "text/xml";
        request.Method = "POST";
        string postData = @"<XMLRequest>
        <RequestType>Destination</RequestType> 
        <RequestLogin>
        <Username></Username> 
        <Password></Password> 
        </RequestLogin>
        </XMLRequest>";
        byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        request.ContentType = "multipart/form-data";
        request.ContentLength = byteArray.Length;

        return View();
    }

*处理到View时,您需要发送一个Post请求,并收到服务器的响应。我已经很久了 遭受这个决定,但没有什么是不可能的。请 救命!!!获取数据的条件:通过HTTPS协议,方法: POST,MIME类型:符合RFC1867的multipart / form-data (http://www.ietf.org/rfc/rfc1867.txt)。请求必须包含三个 参数:

  1. 登录(字符串用户名);
  2. 密码(字符串PASSWORD);
  3. get(list | all | ,, ...)。*

1 个答案:

答案 0 :(得分:0)

我不确定,但在此示例中,您根本不会放置数据。试试

public async Task<ActionResult> About()
{
            WebRequest request = WebRequest.Create("");
            request.ContentType = "text/xml";
            request.Method = "POST";
            string postData = @"<XMLRequest>
            <RequestType>Destination</RequestType> 
            <RequestLogin>
            <Username></Username> 
            <Password></Password> 
            </RequestLogin>
            </XMLRequest>";
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            request.ContentType = "multipart/form-data";
            request.ContentLength = byteArray.Length;
            //Set data...
            var dataStream = await request.GetRequestStreamAsync();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            await request.GetResponseAsync();
            return View();
}

或使用FormUrlEncodedContent

var parameters = new List<KeyValuePair<string, string>> {
         new KeyValuePair<string, string>("username", "YourName"),
         new KeyValuePair<string, string>("password", "YourPassword"),
         new KeyValuePair<string, string>("get", "list")};

var data = new FormUrlEncodedContent(parameters);

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("");
request.Method = "POST";

byte[] dataArray = await data.ReadAsByteArrayAsync();
request.ContentLength = dataArray.Length;
request.ContentType = "application/x-www-form-urlencoded";

var dataStream = await request.GetRequestStreamAsync();
dataStream.Write(dataArray, 0, dataArray.Length);
dataStream.Close();

var resp = await request.GetResponseAsync();
dataStream = resp.GetResponseStream();