使用jQuery / asp.net的WebAPI时,奇怪的行为 [英] Strange Behavior when using jQuery/asp.net WebApi

查看:117
本文介绍了使用jQuery / asp.net的WebAPI时,奇怪的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个网页API项目:

I have 2 Web API Projects:


  • API1是一个测试环境,为JavaScript的前端,但有一个API
    后端(默认Values​​Controller)也用于测试。

  • API2是真正的后端,从该实验的JavaScript UI schould提取数据。为了测试,我使用默认Values​​Controller这里也是如此,因为,我想有相同的输出。

现状


  • 该API1的UI可以从自己的API的Values​​Controller查询的数据

  • The Api1-UI can query the Data from the ValuesController of the own API

该API2返回正确的数据(在Firefox和小提琴手测试)

The Api2 returns the Correct Data(tested in Firefox and with Fiddler)

的code

JavaScript客户端:

JavaScript Client:

    var _load = function (url) {
        $.ajax({
            url: url,
            method: 'GET',
            accepts: "application/json; charset=utf-8",
            success: function (data) {
                alert("Success: " + data);
            },
            error: function (data) {
                alert("Error :" + data);                  
            }
        });
    };

的WebAPI控制器的方法:

WebApi Controller method:

    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

问题

实验前端的UI的JavaScript是无法显示,甚至可以接受,从API 2,这是该数据,按照提琴手,发送正确的。

The JavaScript UI of the experimental Front-End is not able to display, or even receive, the data from the API 2, which is, according to Fiddler, sent correct.

我的第一个想法是,我使用了错误的方法,但我想 $。的getJSON $。阿贾克斯。但是,我总是最后一个错误。它只是说的状态文本=错误
我不明白,为什么它可以从自己的ApiController显示数据,但不能从外部...

My first thought was, I am using the wrong Method, but i tried $.getJSON and $.ajax. But i always end up with an error. It just says statusText= "Error" I don't get, why it can display Data from the own ApiController, but not from the "External"...

感谢您的任何帮助/建议

Thanks for any Help/Suggestions

推荐答案

您似乎是从X的不同的Y域用ajax访问数据。这似乎是一个典型的跨域访问的问题。

You seem to be accessing data from X from a different domain Y using ajax. This seems to be a classic cross domain access issue.

您需要设置的访问控制允许来源以值*在你的响应头。

You need to set Access-Control-Allow-Origin to value " * " in your response header.

 Response.Headers.Add("Access-Control-Allow-Origin", "*")

有多种方法可以解决这个问题。

There various ways you can solve this


  • 在IIS中定义这个头文件

  • 使用actionfilter属性,像下面

FilterAttribute

public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        if (actionExecutedContext.Response != null)
            actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");

        base.OnActionExecuted(actionExecutedContext);
    }
}

控制器上操作使用属性

[AllowCrossSiteJson]
public Result Get(int id)
{
   //return appropriate result
}

这篇关于使用jQuery / asp.net的WebAPI时,奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆