簡體   English   中英

如何從MVC Controller訪問Web Api?

[英]How to access Web Api from MVC Controller?

我創建了一個Web API 2項目,該項目將成為連接數據庫的服務層。

現在,我有兩個不同的MVC 5.2應用程序:一個網站及其CMS ...

在MVC 5.2控制器中,我想訪問API以獲取帖子,創建的帖子等。

  1. 如何從我的MVC控制器訪問api?

  2. 我可以調用API並發送帶有一張要保存的圖片的帖子嗎?

    我怎樣才能做到這一點? 我應該以哪種格式發送集成在PostModel中的圖像?

  3. 如何確保只有兩個MVC應用程序被授權使用API​​?

    所有應用程序都在同一服務器上。

編輯

作者評論:我只希望將服務層(Web API)與網站分開,因為我將有3個使用相同服務層的應用程序:博客,CMS和網站。 如果可能的話,我感謝完整的課程。 謝謝

是的,最好將其分開,不要再依賴添加作為參考。 這是因為有朝一日您可能想在單獨的服務器上進行部署。 或采用不同的部署過程,實施持續集成開發過程。

因此,從我們所有的討論中可以很明顯地看出,您將實現為:

在此處輸入圖片說明

您將如何從其他.Net應用程序調用WebApi?

我要使用的最簡單的方法是在.Net Framework 4.5(?)中添加的HttpClient類。

using (var client = new HttpClient())
    {
        // New code:
        client.BaseAddress = new Uri("http://localhost:9000/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    }
  1. 如何將圖像和數據一起發送到WebApi?

您可以使用我項目中的以下代碼作為參考:

[HttpPost]
        public async Task<IHttpActionResult> UploadFileAsync()
        {
            IHttpActionResult actionResult = null;

            if (Request.Content.IsMimeMultipartContent())
            {
                // Read the file and form data.
                MultipartFormDataMemoryStreamProvider provider = new MultipartFormDataMemoryStreamProvider();
                await Request.Content.ReadAsMultipartAsync(provider);

                // get form data from  like provider.FormData["description"];
                if (!provider.FileStreams.Any())
                {
                    actionResult = BadRequest(ValidationMessages.FileNotFound);
                }
                else
                {
                    var ownerID = 0;
                    var ownerType = provider.FormData.Get("ownerType");
                    int.TryParse(provider.FormData.Get("ownerID"), out ownerID);

                    List<Document> documents = new List<Document>();

                    foreach (KeyValuePair<NameValueCollection, Stream> file in provider.FileStreams)
                    {
                        NameValueCollection fileHeader = file.Key;
                        string fileName = fileHeader.Get("FileName");
                        string contentType = fileHeader.Get("ContentType");
                        Stream stream = file.Value;


                        using (var reader = new BinaryReader(stream))
                        {
                            var fileBytes = reader.ReadBytes((int)stream.Length);

                            var document = new Document()
                            {
                                FileName = fileName,
                                Extension = Path.GetExtension(fileName),
                                Binary = fileBytes,
                                ContentType = contentType,
                                Size = fileBytes.LongLength
                            };

                            if (ownerID > 0)
                            {
                                document.RequestID = ownerID;
                            }

                            documents.Add(document);
                        }
                    }

                    if (documents.Count() > 0)
                    {
                        string exceptionMessages = string.Empty;
                        if (this.DomainService.InsertRange(documents, out exceptionMessages))
                        {
                            actionResult = Created(string.Empty, documents);
                        }
                        else
                        {
                            actionResult = BadRequest(exceptionMessages);
                        }
                    }
                    else
                    {
                        actionResult = BadRequest(ValidationMessages.FileNotFound);
                    }
                }
            }
            else
            {
                // The response to upload did not came with Multiple content;
                actionResult = BadRequest(ValidationMessages.MimeNotFound);
            }

            return actionResult;
        }


using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;

namespace Webapi.Helper
{
    public class MultipartFormDataMemoryStreamProvider : MultipartMemoryStreamProvider
    {
        private readonly Collection<bool> _isFormData = new Collection<bool>();
        private readonly NameValueCollection _formData = new NameValueCollection(StringComparer.OrdinalIgnoreCase);
        private readonly Dictionary<NameValueCollection, Stream> _fileStreams = new Dictionary<NameValueCollection, Stream>();

        public NameValueCollection FormData
        {
            get { return _formData; }
        }

        public Dictionary<NameValueCollection, Stream> FileStreams
        {
            get { return _fileStreams; }
        }

        public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)
        {
            if (parent == null)
            {
                throw new ArgumentNullException("parent");
            }

            if (headers == null)
            {
                throw new ArgumentNullException("headers");
            }


            var contentDisposition = headers.ContentDisposition;
            if (contentDisposition == null)
            {
                throw new InvalidOperationException("Did not find required 'Content-Disposition' header field in MIME multipart body part.");
            }

            _isFormData.Add(String.IsNullOrEmpty(contentDisposition.FileName));
            return base.GetStream(parent, headers);
        }

        public override async Task ExecutePostProcessingAsync()
        {
            for (var index = 0; index < Contents.Count; index++)
            {
                HttpContent formContent = Contents[index];
                if (_isFormData[index])
                {
                    // Field
                    string formFieldName = UnquoteToken(formContent.Headers.ContentDisposition.Name) ?? string.Empty;
                    string formFieldValue = await formContent.ReadAsStringAsync();
                    FormData.Add(formFieldName, formFieldValue);
                }
                else
                {
                    Stream stream = await formContent.ReadAsStreamAsync(); // File
                    /// we are not going to accept any stream that has no value!!
                    if (stream.Length > 0)
                    {
                        string fileName = UnquoteToken(formContent.Headers.ContentDisposition.FileName);

                        NameValueCollection fileHeader = new NameValueCollection();
                        fileHeader.Add("FileName", fileName);
                        fileHeader.Add("ContentType", UnquoteToken(formContent.Headers.ContentType.MediaType));
                        FileStreams.Add(fileHeader, stream);
                    }
                }
            }
        }

        private static string UnquoteToken(string token)
        {
            if (string.IsNullOrWhiteSpace(token))
            {
                return token;
            }

            if (token.StartsWith("\"", StringComparison.Ordinal) && token.EndsWith("\"", StringComparison.Ordinal) && token.Length > 1)
            {
                return token.Substring(1, token.Length - 2);
            }

            return token;
        }
    }
}

我該如何確保只有我的應用程序可以與WebApi連接?

簡短的答案是,您可以通過遵循此體系結構來使用在應用程序之間共享的私鑰。

在此處輸入圖片說明 網上有很多代碼可以幫助您解決此問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM