惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Secure Thoughts
Security Latest
Security Latest
Simon Willison's Weblog
Simon Willison's Weblog
O
OpenAI News
GbyAI
GbyAI
L
LINUX DO - 最新话题
A
Arctic Wolf
T
Tor Project blog
G
GRAHAM CLULEY
I
InfoQ
博客园_首页
IT之家
IT之家
The Register - Security
The Register - Security
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
P
Proofpoint News Feed
The GitHub Blog
The GitHub Blog
Blog — PlanetScale
Blog — PlanetScale
N
Netflix TechBlog - Medium
K
Kaspersky official blog
博客园 - 三生石上(FineUI控件)
S
SegmentFault 最新的问题
U
Unit 42
PCI Perspectives
PCI Perspectives
量子位
P
Palo Alto Networks Blog
S
Securelist
T
Troy Hunt's Blog
博客园 - 【当耐特】
Recorded Future
Recorded Future
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
S
Security Affairs
Engineering at Meta
Engineering at Meta
T
The Blog of Author Tim Ferriss
博客园 - 聂微东
罗磊的独立博客
N
News and Events Feed by Topic
人人都是产品经理
人人都是产品经理
B
Blog RSS Feed
NISL@THU
NISL@THU
C
Cisco Blogs
T
Threatpost
有赞技术团队
有赞技术团队
Forbes - Security
Forbes - Security
Hugging Face - Blog
Hugging Face - Blog
Last Week in AI
Last Week in AI
T
The Exploit Database - CXSecurity.com
Cloudbric
Cloudbric
Cyberwarzone
Cyberwarzone
Google DeepMind News
Google DeepMind News
C
Cyber Attacks, Cyber Crime and Cyber Security

博客园 - 小马过河MJ

Identity Server introspect 调用 /connect/introspect windows forget jenkins password. 转载(Asp.net Core 中试使用ZKWeb.System.Drawing) EFCore & Mysql migration on Production HTML to PDF pechkin Log4net 为MVC 添加下载权限 辞职 MiniProfiler Android Studio 设置LogCat 颜色 运用Swagger 添加WebAPI 文档 给现有MVC 项目添加 WebAPI Summernote async await MVC 伪静态 设置EntityFramework 在开发时自动更新数据库 PagedList.MVC 应用 MVC 自定义错误处理 SQL Server 索引结构及其使用(四)[转] SQL Server 索引结构及其使用(三)[转]
跨域调用WebApi
小马过河MJ · 2016-02-05 · via 博客园 - 小马过河MJ

1. WebApi 和WebConfig 设置

using Libaray.DAL.Services;
using Libaray.Models.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace Libaray.WebApi.Controllers
{
    /// <summary>
    /// 图书信息
    /// </summary>
    public class BookController : ApiController
    {
        BookService BookDAL = new BookService();

        /// <summary>
        /// 查询所有图书信息
        /// </summary>
        /// <returns></returns>
        public IQueryable<BookModel> Get()
        {
            return BookDAL.FindList<BookModel>().AsQueryable();
        }

        /// <summary>
        /// 查询制定Id的图书信息
        /// </summary>
        /// <param name="id">图书Id</param>
        /// <returns>查询到的图书信息</returns>
        public BookModel Get(string id)
        {
            Guid BookId = Guid.Parse(id);
            return BookDAL.Find(u => u.BookId == BookId);
           
        }
    }
}
 <system.webServer>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    <validation validateIntegratedModeConfiguration="false" />
    <modules>
      <remove name="ApplicationInsightsWebTracking" />
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
    </modules>
    <httpProtocol>  <!-- 重点开始 -->
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Max-Age" value="30"/>
      <add name="Access-Control-Allow-Methods" value="GET,POST,OPTIONS"/>
      <add name="Access-Control-Allow-Headers" value="Content-Type, Accept" />
    </customHeaders>
  </httpProtocol>  <!-- 重点结束 -->
  </system.webServer>

2. MVC 客户端

@{
    ViewBag.Title = "FindBook";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>FindBook</h2>

<div class="row" style="margin-top:20px;">
    <div class="col-sm-2">
        @Html.Partial("_AccountNavigator")
    </div>
    <div class="col-sm-10">
        <form id="form" action="/Book/FindBook" method="get">
            <div class="form-horizontal">
                <div class="form-group">
                    <label class="col-sm-1 control-label">图书Id</label>
                    <div class="col-sm-2">
                        @Html.TextBox("BookId", "", new { @class= "form-control input-sm" })
                        <input type="text" id="test" name="test" />
                    </div>
                    <input type="submit" value="查找" class="btn btn-sm btn-default" />
                </div>
            </div>
        </form>
        <div class="table-responsive">
            <table class="table table-striped table-hover">
                <thead>
                    <tr>
                        <td>BookId</td>
                        <td>Book Name</td>
                        <td>Author</td>
                    </tr>
                </thead>
                <tbody id="tb"></tbody>
            </table>
        </div>
    </div>
</div>
<script type="text/javascript">
    $(function () {
        $.getJSON("http://localhost:50159/api/book", function (data) {
            $.each(data, function (key, item) {
                $("#tb").append("<tr><td>" + item.BookId + "</td><td>" + item.BookName + "</td>" + "<td>" + item.Author + "</td></tr>");
            });
        });
    })
</script>

Controller 

  [HttpGet]
        public async Task<ActionResult> FindBook(string BookId)
        {
            if(!string.IsNullOrEmpty(BookId))
            {
                string url = "http://localhost:50159/api/book/";
                var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
                using (var http = new HttpClient(handler))
                {
                    var data = await http.GetAsync(url);

                    var content = data.Content.ReadAsStringAsync();

                    return View(data);
                }
            }
            return View();
        }