本文介绍了我怎样的WebAPI处理JSONP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  

我有我的WebAPI一个get方法,该方法如下:

I have a get method for my WebAPI which is as follows:

    private T Get<T>(string uri)
    {
        T result = default(T);
        bool isSuccess = true;

        client
            .GetAsync(uri)
            .ContinueWith(task =>
            {
                // EnsureStatus
                isSuccess = task.Result.IsSuccessStatusCode;
                task
                .Result
                .Content
                .ReadAsAsync<T>()
                .ContinueWith(t => result = t.Result)
                .Wait();
            })
            .Wait();
       return result;
     }

其结果是在一个JSON格式生成,但我想为JSONP。

The result is produced in a JSON format but I want it for JSONP.

我已阅读, ReadAsSync 只能处理内置mediaformatters。那么,有没有一种方法,我可以改变它来处理JSONP?

I have read that ReadAsSync only handles built in mediaformatters. So is there a way I can change it to handle JsonP?

推荐答案

这个盗窃重复 ....

要完成你想要什么,你需要三样东西:

To accomplish what you want you need three things :


  1. 要添加媒体格式,输出JSONP

  2. 注册媒体格式(传统上通过global.asx完成)

  3. 确保客户端请求JSONP。

  1. to add a media formatter that outputs JSONP
  2. register the media formatter (traditionally done through global.asx)
  3. ensure the client requests jsonP.

您可以偷这个JSONP媒体格式。

You can steal this JSONP media formatter.

然后,您需要注册媒体格式。你可以用下面的code编程片段做到这一点:

Then, you need to register the media formatter. You can do this programatically with the following code snippet:

var config = GlobalConfiguration.Configuration;
config.Formatters.Insert(0, new JsonpMediaTypeFormatter());

既然你显然不使用Global.asax中你将需要确保格式化某种方式登记。你不提供关于如何做到这一点足够的信息,但我怀疑一个明智放在IF语句和一个静态变量,表示注册将得到你。

Since you apparently don't use global.asax you're going to need to make sure the formatter is registered somehow. YOU don't provide enough information on how to do it, but i suspect a judiciously placed IF statement and a static variable indicating registration would get you there.

我还是不太知道你使用的是什么类型的客户端,但如果它的jQuery像下面将让你有:

I still don't quite know what type of client you're using, but if it's jquery something like the following will get you there:

$.ajax({
    url: 'http://myurl.com',
    type: 'GET',
    dataType: 'jsonp',
    success: function (data) {
        alert(data.MyProperty);
    }
})

重要的部分是发送接受头相匹配的接受你的头闪亮的新JSONP格式正在监听。在我看来,前两个选择要么是:应用程序/ JavaScript的文/ JavaScript的

The important part is the accept header sent matches the accept header your shiny new jsonp formatter is listening for. The top two choices in my opinion are either: application/javascript or text/javascript.

这篇关于我怎样的WebAPI处理JSONP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 07:23