Показаны сообщения с ярлыком ASP.NET MVC. Показать все сообщения
Показаны сообщения с ярлыком ASP.NET MVC. Показать все сообщения

вторник, 6 октября 2020 г.

ASP.NET MVC: одинаковый IP адрес клиента (Request.UserHostAddress) после настройки переадресации с HTTP на HTTPS

Ситуация и проблема 

Есть приложение ASP.NET MVC. В приложении записывааются IP адреса клиентов для статистики через 

Request.UserHostAddress

В какой то момент понадобилась переадресация с http на https, которая была сделана через рерайт в веб-конфиге. И значение Request.UserHostAddress стало показывать всегда один и тот же адрес (адрес сервера хостинга).

Решение

Использовать поле 

Request.Headers["X-Forwarded-For"] 

в нем, в моем случае, через запятую были 2 IP-адреса. Взяли из них первый.

Код получился примерно такой

var IPv4Address = "";

var headerValueXForwerdedFor = request.Headers["X-Forwarded-For"];

if (string.IsNullOrWhiteSpace(headerValueXForwerdedFor))

{

  IPv4Address = request?.UserHostAddress;

}

else

{

  var XForwardedForIpAddress = headerValueXForwerdedFor;

  var commaindex = headerValueXForwerdedFor.IndexOf(',');

  if (commaindex > 0)

  {

  XForwardedForIpAddress = headerValueXForwerdedFor.Substring(0, commaindex);

  }  

   IPv4Address = XForwardedForIpAddress;

 }


Что помогло: 

статья со StackOwerflow

https://stackoverflow.com/questions/15297620/request-userhostaddress-return-ip-address-of-load-balancer

воскресенье, 12 апреля 2020 г.

C# Как убрать порт по умолчанию при генерации адреса с помощью UriBuilder

Проблема


есть такой код по преобраpованию ссылки

var uriBuilder = new UriBuilder(absoluteUri);
//(код модифицирующий url с помощью механизмов UriBuilder)
...
uriBuilder.ToString()

uriBuilder.ToString() генерирует ссылку с явным указанием порта, даже если порта во входной строке не было

Пример
вход: https://a.b.com/test
выход:https://a.b.com:443/test

Что помогло

Статья
How to remove the port number from a url string
https://stackoverflow.com/questions/2819336/how-to-remove-the-port-number-from-a-url-string

Решение

написал такой вспомогательный метод

private static string GetUriBuilderAsStringWithoutDefaultPort(UriBuilder uriBuilder)
        {
            if (uriBuilder.Uri.IsDefaultPort) uriBuilder.Port = -1;
            return uriBuilder.ToString();
        }

и теперь вместо UriBuilder.ToString() вызваю GetUriBuilderAsStringWithoutDefaultPort(uriBuilder)


C# пример SEO оформления страниц сайта с пейджингом (с учетом рекомендаций Google)

Задача


Оформить дружелюбно для поиска Google страницы сайта с пейджингом

Теория

На английском
SEO Guide to Google Webmaster Recommendations for Pagination
https://moz.com/blog/seo-guide-to-google-webmaster-recommendations-for-pagination

На русском
Постраничная верстка rel=«next|prev»
https://habr.com/ru/post/128746/

Сухая выжимка.
Для страниц каталога , которые реализованы в виде пейджинга рекомендуется прописывать в заголовке страницы

<link rel="prev" href="http://www.example.com/article?story=abc&page=2" /> <link rel="next" href="http://www.example.com/article?story=abc&page=4" />


причем   link rel="prev" не нужен на первой странице, а
link rel="next" не нужен на последней

Решение на C#

public static class UtilsSeo
    {
        private const string pageParamName = "page";

        public static string FindUrlPagePrev(
            string url,
            int? pageNumber,
            int pageSize,
            int itemTotalCount
        )
        {
            var pageNumberStrongDefined = GetStrongDefinedPageNumber(pageNumber);

            if (pageNumberStrongDefined <= 1) return null;

            if (pageNumberStrongDefined > GetMaxPageNumber(pageSize, itemTotalCount)) return null;

            return devuaUtils2014.Urls.UrlParamAddOrChange(url, pageParamName, (pageNumberStrongDefined - 1).ToString());
        }

        private static int GetStrongDefinedPageNumber(int? pageNumber)
        {
            var pageNumberStrongDefined = pageNumber ?? 0;
            if (pageNumberStrongDefined <= 0) pageNumberStrongDefined = 1;
            return pageNumberStrongDefined;
        }

        public static bool IsLastPage(
            int? pageNumber,
            int pageSize,
            int itemTotalCount
            )
        {
           return GetStrongDefinedPageNumber(pageNumber) >= GetMaxPageNumber(pageSize, itemTotalCount);
        }

        private static double GetMaxPageNumber(int pageSize, int itemTotalCount)
        {
            return Math.Ceiling( (double)itemTotalCount / (double)pageSize );
        }

        public static string FindUrlPageNext(
            string url,
            int? pageNumber,
            int pageSize,
            int itemTotalCount
        )
        {
            if (IsLastPage(pageNumber, pageSize, itemTotalCount)) return null;

            var pageNumberStrongDefined = GetStrongDefinedPageNumber(pageNumber);
            
            return devuaUtils2014.Urls.UrlParamAddOrChange(url, pageParamName,
                (pageNumberStrongDefined + 1).ToString());
        }

    }

Утилиты

namespace devuaUtils2014
{
    public static class Urls
    {
        public static string UrlParamRemove(string absoluteUri, string paramName)
        {
            var uriBuilder = new UriBuilder(absoluteUri);
            var query = HttpUtility.ParseQueryString(uriBuilder.Query);
            query.Remove(paramName);
            uriBuilder.Query = query.ToString();
            return GetUriBuilderAsStringWithoutDefaultPort(uriBuilder);
        }

        private static string GetUriBuilderAsStringWithoutDefaultPort(UriBuilder uriBuilder)
        {
            if (uriBuilder.Uri.IsDefaultPort)
            {
                uriBuilder.Port = -1;
            }
            return uriBuilder.ToString();
        }

        public static string UrlParamChange(string absoluteUri, string paramName, string paramValue)
        {
            var uriBuilder = new UriBuilder(absoluteUri);
            var query = HttpUtility.ParseQueryString(uriBuilder.Query);
            query[paramName] = paramValue;
            uriBuilder.Query = query.ToString();
            
            return GetUriBuilderAsStringWithoutDefaultPort(uriBuilder);
        }


        public static string UrlParamAdd(string absoluteUri, string paramName, string paramValue)
        {
            var uriBuilder = new UriBuilder(absoluteUri);
            var query = HttpUtility.ParseQueryString(uriBuilder.Query);
            query.Add(paramName,paramValue); //[paramName] = paramValue;
            uriBuilder.Query = query.ToString();
            
            return GetUriBuilderAsStringWithoutDefaultPort(uriBuilder);
        }

        public static string UrlParamAddOrChange(string absoluteUri, string paramName, string paramValue)
        {
            var uriBuilder = new UriBuilder(absoluteUri);
            var query = HttpUtility.ParseQueryString(uriBuilder.Query);
            var res = "";
            if (string.IsNullOrEmpty(query[paramName]))
            {
                res = UrlParamAdd(absoluteUri, paramName, paramValue);
            }
            else
            {
                res = UrlParamChange(absoluteUri, paramName, paramValue);
            } 
            return res;
        }
    }
}

Пример
https://childcourse.com.ua/course?page=2

суббота, 29 декабря 2018 г.

ASP.NET MVC Ошибка при загрузке fontawesome-webfont.woff2 ERR_ABORTED 404 (Not Found)


Проблема: 

анализирую загрузку веб страницы (сайт на ASP.NET MVC) через средства разработчика Chrome

наблюдаю ошибку загрузки одного ресурса,

GET https://(сайт)/Content/themes/SbAdmin2/font-awesome-4.7.0/fonts/fontawesome-webfont.woff2?v=4.7.0 net::ERR_ABORTED 404 (Not Found)

причем, проверю по ftp: файл в директории есть

Погуглил:
если вкратце, то ошибка появляется из-за того что настройки веб-сервера не воспринимают расширение .woff2 как статический контент.

Нужно помочь в єтом веб серверу.

Делается через web.config. Нужно добавить несколько строк в разделе system.webServer / staticContent

Добавленные строки выделил

 <system.webServer>
    <staticContent>
      <clientCache cacheControlCustom="public" cacheControlMode="UseMaxAge" cacheControlMaxAge="365.00:00:00" />
  <remove fileExtension=".woff" />
      <remove fileExtension=".woff2" />
      <mimeMap fileExtension=".woff" mimeType="application/x-font-woff" />
      <mimeMap fileExtension=".woff2" mimeType="application/font-woff2" />
    </staticContent>



Материалы по теме
HTTP 404 Not Found Error with .woff or .woff2 Font Files
https://hotcakescommerce.zendesk.com/hc/en-us/articles/210926903-HTTP-404-Not-Found-Error-with-woff-or-woff2-Font-Files


How to solve glyphicons-halflings-regular.woff2 Err_Aborted issue in ASP.Net MVC 5
https://stackoverflow.com/questions/46508793/how-to-solve-glyphicons-halflings-regular-woff2-err-aborted-issue-in-asp-net-mvc

пятница, 1 декабря 2017 г.

ASP.NET Ошибка приложения: Заданный аргумент находится вне диапазона допустимых значений. Имя параметра: site

Окружение

Visual Studio 2017, ASP.NET MVC проект

Ошибка


При запуске веб-приложения получил ошибку

Заданный аргумент находится вне диапазона допустимых значений.
Имя параметра: site

Трассировка стека:

[ArgumentOutOfRangeException: Заданный аргумент находится вне диапазона допустимых значений.
Имя параметра: site]
   System.Web.HttpRuntime.HostingInit(HostingEnvironmentFlags hostingFlags, PolicyLevel policyLevel, Exception appDomainCreationException) +280

[HttpException (0x80004005): Заданный аргумент находится вне диапазона допустимых значений.
Имя параметра: site]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +10042604
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +95
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254



Английская версия ошибки
Specified argument was out of the range of valid values.Parameter name: site


Решение

Фактически сделал такие действия


  • переобновил через панель установки приложений IIS Express

  • сбросил через диспетчер задач запущенный процесс IIS Express

После этого приложение заработало нормально

Помогла статья
https://stackoverflow.com/questions/17772216/specified-argument-was-out-of-the-range-of-valid-values-parameter-name-site

среда, 11 января 2017 г.

ASP.NET MVC Пейджинг

Ссылки на модули пейджинга на ASP.NET.MVC

mvcpaging
http://nugetmusthaves.com/Tag/paging

я пользовался
http://nugetmusthaves.com/Package/MvcPaging

ASP.NET MVC логирование




----------
логирование asp.net mvc

http://www.internet-technologies.ru/articles/article_727.html
http://stackoverflow.com/questions/1822754/log-user-activity-on-asp-net-mvc-application
http://rion.io/2013/03/03/implementing-audit-trails-using-asp-net-mvc-actionfilters/
http://scottlilly.com/how-to-log-your-users-controller-actions-for-an-asp-net-mvc-4-website/

ASP.NET MVC высоконагруженные приложения. Подборка ссылок


ASP.NET MVC - как построить по-настоящему гибкое веб-приложение
http://www.slideshare.net/AlexanderByndyu/aspnet-mvc-7557204


Building high-performance ASP.NET applications
https://aspguy.wordpress.com/2014/02/17/building-high-performance-asp-net-applications/


Is ASP.Net a technology suitable for high-load sites?
http://stackoverflow.com/questions/354201/is-asp-net-a-technology-suitable-for-high-load-sites


Я хочу, чтобы сайты открывались мгновенно
http://habrahabr.ru/post/274129/


Моментальная загрузка десктопных и мобильных сайтов: часть 1
http://habrahabr.ru/company/mobilizetoday/blog/269397/


Asp.NET MVC - отправка почты в отдельном потоке




Asp.NET MVC - отправка почты в отдельном потоке

ASP.Net MVC background threads for email creation and sending
http://stackoverflow.com/questions/3637649/asp-net-mvc-background-threads-for-email-creation-and-sending

Sending Mail in Background with ASP.NET MVC
http://hangfirechinese.readthedocs.org/en/latest/tutorials/send-email.html

Building high-performance ASP.NET applications
https://aspguy.wordpress.com/2014/02/17/building-high-performance-asp-net-applications/

Send email in background thread in C# aps.net
http://www.advancesharp.com/blog/1107/send-email-in-background-thread-in-c-aps-net

How To Send Email In ASP.NET MVC
http://www.mikesdotnetting.com/article/268/how-to-send-email-in-asp-net-mvc

How to send email Asynchronously in ASP.Net using Background Thread
http://www.aspsnippets.com/Articles/How-to-send-email-Asynchronously-in-ASPNet-using-Background-Thread.aspx

ASP.NET MVC Урок A. Уведомление и рассылка
http://habrahabr.ru/post/176075/

ASP.NET MVC Bundling and minification

Собрал здесь ссылки по теме

Bundling and Minification
http://www.asp.net/mvc/overview/performance/bundling-and-minification

Добавляем Bundling and Minification в приложение ASP.NET Web Forms
https://habrahabr.ru/post/150863/

ASP.NET MVC страница остановки приложения

Собрал здесь ссылки по теме

asp.net mvc страница остановки приложения

app_offline.html

http://stackoverflow.com/questions/4181978/site-is-under-construction-page-for-asp-net-site
http://blog.kurtschindler.net/app_offline-htm-gotchas-with-asp-net-mvc/

App_Offline.htm
http://weblogs.asp.net/scottgu/426755

Take an MVC web site offline and back online
http://stackoverflow.com/questions/20911678/take-an-mvc-web-site-offline-and-back-online

Как написать простой блог с помощью Asp .Net MVC, Nhibernate и Nineject

Сохраню здесь ссылку

Как написать простой блог с помощью Asp .Net MVC, Nhibernate и Nineject.Часть 1
https://habrahabr.ru/post/278633/

вторник, 10 января 2017 г.

ASP.NET MVC Caching links 2016

----

asp.net: описание механизма кэширования страниц через OutputCache
http://habrahabr.ru/post/26146/

Кеширование в ASP.NET MVC
http://habrahabr.ru/post/168869/

How to cache data in a MVC application
http://stackoverflow.com/questions/343899/how-to-cache-data-in-a-mvc-application

Improving Performance with Output Caching (C#)
http://www.asp.net/mvc/overview/older-versions-1/controllers-and-routing/improving-performance-with-output-caching-cs

Кеширование на уровне контроллеров в ASP.NET MVC
http://codehelper.ru/questions/178/new/%D0%BA%D0%B5%D1%88%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5-%D0%BD%D0%B0-%D1%83%D1%80%D0%BE%D0%B2%D0%BD%D0%B5-%D0%BA%D0%BE%D0%BD%D1%82%D1%80%D0%BE%D0%BB%D0%BB%D0%B5%D1%80%D0%BE%D0%B2-%D0%B2-aspnet-mvc

про очистку
How to programmatically clear outputcache for controller action method
http://stackoverflow.com/questions/1167890/how-to-programmatically-clear-outputcache-for-controller-action-method

MVC 4.0 Clearing output cache using HttpResponse.RemoveOutputCacheItem
http://stackoverflow.com/questions/21296357/mvc-4-0-clearing-output-cache-using-httpresponse-removeoutputcacheitem

How to clear outputcache?
http://forums.asp.net/t/1702268.aspx?How+to+clear+outputcache+

How to Clear OutputCache for Website without Restarting App
http://stackoverflow.com/questions/37101/how-to-clear-outputcache-for-website-without-restarting-app

Programmatically Clearing the ASP.Net Cache for Web Forms and MVC Pages
http://dotnet.dzone.com/articles/programmatically-clearing-0

Flushing the ASP.NET Output cache using code
http://www.danesparza.net/2013/01/flushing-the-asp-net-output-cache-using-code/

суббота, 19 ноября 2016 г.

ASP.NET error The compiler failed with error code -1073741502

Problem


Suddenly I Receive such error on remote ASP.NET hosting after publishing site.

Server Error in '/' Application.

Compilation Error

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: The compiler failed with error code -1073741502.




Solution

Solution is described here
http://stackoverflow.com/questions/6817870/asp-net-strange-compilation-error

четверг, 22 сентября 2016 г.

ASP.NET MVC ошибка Index was outside the bounds of the array

Окружение

Visual Studio 2015, проект на ASP.NET MVC со сломанными референсами. Референсы перестраивал.

Проблема

при запуске проекта

получаю ошибку

Английский вариант
Index was outside the bounds of the array

красная строка:
@Styles.Render("[имя бандла стилей]")


Решение

Помогло обновление через NuGet библиотеки WebGrease

Люди пишут, что иногда нужно обновлять и Microsoft ASP.NET Web Optimization Framework

См. также

Еще варианты описаны в статье

суббота, 28 ноября 2015 г.

ASP.Net MVC Html.ActionLink проблемы при передаче routeValues как переменной

Ситуация

Во View была строка

@Html.ActionLink("Заказать", "add", "order",
new {id=Model.Id, feedbackid=Model.FeedbackId},
      new {rel="nofollow"})


т.к. набор параметров был опциональный - захотелось их вынести в отдельную переменную

код стал таким
@{
var addOrderLinkRouteValues = new RouteValueDictionary();
addOrderLinkRouteValues.Add("Id", Model.Id);
// опциональное добавление других параметров
}
...
@Html.ActionLink("Заказать", "add", "order",
        addOrderLinkRouteValues,
      new {rel="nofollow"})

Проблема

испортилась ссылка. вместо набора параметров в ссылке на выходе стало отображаться название типа 

/order/add?Count=1&Keys=System.Collections.Generic.Dictionary%602%2BKeyCollection%5BSystem.String%2CSystem.Object%5D&Values=System.Collections.Generic.Dictionary%602%2BValueCollection%5BSystem.String%2CSystem.Object%5D

Решение

Если в двух словах. при таком использовании система подхватывает не тот перегруженный метод

подхватывается такой 
ActionLink(HtmlHelper, String, String, String, Object, Object)
а нам нужен быть такой
ActionLink(HtmlHelper, String, String, RouteValueDictionary, IDictionary<String, Object>)

соответственно код нужно заменить на такой 

@Html.ActionLink("Заказать", "add", "order",
addOrderLinkRouteValues,
        new Dictionary<string, object>{
        {"rel","nofollow"}
            }
        )
тут последний параметр задан типом Dictionary (реализующим IDictionary) а не объектом

среда, 30 сентября 2015 г.

Entity Framework: Reload newly created object / Reload navigation properties

Environment

ASP.NET MVC 4 application, EntityFramework 6

Problem


Unable to reload the updated properties of an object from the database, and navigation properties.

Scenario

I do processing Post-request for object creation in the controller's action .
The object itself passed in the Action as parameter.

I usually do this sequence

...
check values
save object
additional actions after saving
...

From the client side a new object comes "clean" / without navigational properties.
I add it to the context and save.
Once saved, I want to do the extra processing in which I need the navigation properties,
but the problem is that EF caches object and reloading does not update the navigation properties. They remain empty.

Solution

Before you read the object from database it must be disconnected from the context.

I got to do it this way:

public void Detach (T entity)
{
            ((IObjectContextAdapter) _db) .ObjectContext.Detach (entity);
}

The solution found here
Entity Framework Code First - No Detach () method on DbContext
http://stackoverflow.com/questions/4168073/entity-framework-code-first-no-detach-method-on-dbcontext

Related Links


Entity Framework Code First - No Detach() method on DbContext
http://stackoverflow.com/questions/4168073/entity-framework-code-first-no-detach-method-on-dbcontext

Reload an entity and all Navigation Property Association- DbSet Entity Framework
http://stackoverflow.com/questions/9081244/reload-an-entity-and-all-navigation-property-association-dbset-entity-framework

How to update an entity's navigation properties in Entity Framework
http://stackoverflow.com/questions/10542209/how-to-update-an-entitys-navigation-properties-in-entity-framework

Entity Framework POCO - Refresh a navigation property
http://stackoverflow.com/questions/3839166/entity-framework-poco-refresh-a-navigation-property

Entity Framework Перезагрузить только что созданный объект/перегрузить навигационные свойства

Окружение

ASP.NET MVC 4 приложение, EntityFramework 6

Проблема

Не получается перезагрузить обновленные свойства объекта из базы данных и навигационные свойства


Сценарий использования

Обрабатываю в контроллере Post-запрос на создание объекта. Объект передается параметром в Экшене.
как обычно я делаю

...
проверки
сохранение объекта
дополнительные действия после сохранения
...

С клиента новый объект приходит "чистым"/ т.е. без навигационных свойств.
Его я и добавляю в контекст и сохраняю.
После сохранения я хочу провести дополнительную обработку в которой мне нужны навигационные свойства, но проблема в том, что EF кеширует объект и повторная загрузка не приводит к обновлению навигационных свойств. Они остаются пустыми.

Решение

Перед тем как считать обновленный объект его нужно отсоединить от контекста.

У меня получилось сделать это так:

public void Detach(T entity)
{
            ((IObjectContextAdapter)_db).ObjectContext.Detach(entity);
}

Решение нашел здесь
Entity Framework Code First - No Detach() method on DbContext
http://stackoverflow.com/questions/4168073/entity-framework-code-first-no-detach-method-on-dbcontext

Ссылки по теме


Entity Framework Code First - No Detach() method on DbContext
http://stackoverflow.com/questions/4168073/entity-framework-code-first-no-detach-method-on-dbcontext

Reload an entity and all Navigation Property Association- DbSet Entity Framework
http://stackoverflow.com/questions/9081244/reload-an-entity-and-all-navigation-property-association-dbset-entity-framework

How to update an entity's navigation properties in Entity Framework
http://stackoverflow.com/questions/10542209/how-to-update-an-entitys-navigation-properties-in-entity-framework

Entity Framework POCO - Refresh a navigation property
http://stackoverflow.com/questions/3839166/entity-framework-poco-refresh-a-navigation-property



среда, 17 декабря 2014 г.

Html.DevExpress().TextBox - привязка к полю Number

Окружение

VS 2013 , Developer Express компоненты DXperience 14.1.8

Проблема

Возникла проблема с полем в БД с именем "Number", точнее, с отображением его в виде текстбокса.

вторник, 26 августа 2014 г.

API Privat24 (Приват24) Пример расчета сигнатуры на C# ASP.NET MVC

Ситуация

Делаю интерфейс к системе онлайн платежей Приват24 (Интернет-эквайринг ПриватБанка)
на ASP.NET MVC (код соответственно на C#)
Документация к системе есть здесь
https://api.privatbank.ua/article/4/

По документации сделал правильную форму для отправки на сервер.

Возникла проблема с разбором ответа

Проблема

Нужно сверить сигнатуру в приватбанковском ответе о платеже.
Но в документации примеры только на PHP.
Решение задачи "в лоб" приводило к неправильной сигнатуре. Пришлось повозиться.
Здесь делюсь результатами.
Примечание: эта статья посвящена только разбору сигнатуры. Остальные вопросы оставил пока за скобками (чтобы не распыляться). Если будет интересно - пишите запросы в комментариях.

Решение

Сначала несколько "помогаторов" (вспомогательные методы)

Помогатор 0

Используем модули

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;

Помогатор 1

Преобразователь массива байтов в строку

        /// <summary>
        /// Возвращает массив байтов в виде шестнадцатиричной строки
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        private static string GetByteArrayAsHexadecimalString(IEnumerable<byte> buffer)
        {
            return buffer.Select(b => b.ToString("x2")).Aggregate("", (total, cur) => total + cur);
        }


Помогатор 2

Рассчитыватель сигнатуры

        /// <summary>
        /// вычисление сигнатуры приват24
        /// </summary>
        /// <param name="payment"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        private static string ComputeSignature(string payment, string password)
        {
            var str = payment + password;
            var sha1 = System.Security.Cryptography.SHA1.Create();
            var md5 = System.Security.Cryptography.MD5.Create();            

            var md5Res = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
            var md5ResString = GetByteArrayAsHexadecimalString(md5Res);

            var sha1Res = sha1.ComputeHash(Encoding.UTF8.GetBytes(md5ResString));
            var sha1ResString = GetByteArrayAsHexadecimalString(sha1Res);
            return sha1ResString;
        }

Помогатор 3

Превращение полей POST-запроса в словарь (Dictionary<string,string>).
Эту строчку применил в экшене контроллера, чтобы дальше уже работать со словарем, а не с полями формы.

var dic = Request.Form.AllKeys.ToDictionary(key => key, key => Request.Form[key]);

Основной метод

Сверка сигнатуры в ответе системы приват24

        public void ParseResult(Dictionary<string, string> fields)
        {
            var passedsignature = fields["signature"];
            var payment = fields["payment"];
            var computedsignature = ComputeSignature(payment, _merchInfo.Password);
            if (passedsignature == computedsignature)
            {
                Console.WriteLine("Bingo!");
                // тут логика разбора ответа
                // ...
            }
            else
            {
                Console.WriteLine("Сигнатуры не совпадают!");
            }                       
        }